package port

import (
	"net"
	"strconv"
	"time"
)

// CheckTCP 检测TCP端口，返回检测结果
func (pc *PortChecker) CheckTCP(host string, port int) *PortCheckResult {
	result := &PortCheckResult{
		Host:   host,
		Port:   port,
		Sent:   pc.Count,
		Delays: make([]time.Duration, 0, pc.Count),
	}
	address := net.JoinHostPort(host, strconv.Itoa(port))
	var totalBytes int64
	for i := 0; i < pc.Count; i++ {
		start := time.Now()
		conn, err := net.DialTimeout("tcp", address, time.Duration(pc.Timeout)*time.Second)
		cost := time.Since(start)
		if err == nil {
			result.Success++
			result.Delays = append(result.Delays, cost)
			// 测试速率：发送少量数据并读取响应（如有）
			msg := []byte("gns_port_test")
			conn.SetDeadline(time.Now().Add(time.Duration(pc.Timeout) * time.Second))
			conn.Write(msg)
			buf := make([]byte, 1024)
			n, _ := conn.Read(buf)
			totalBytes += int64(n)
			conn.Close()
		} else {
			result.Failed++
		}
		time.Sleep(200 * time.Millisecond)
	}
	if result.Success > 0 && len(result.Delays) > 0 {
		result.CalculateStats()
		if result.AvgDelay > 0 {
			result.Speed = float64(totalBytes) / result.AvgDelay.Seconds()
		}
	}
	return result
}
